<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

namespace App\Services\Impl;

use App\Events\SmsSent;
use App\Models\SmsLog;
use App\Services\ICacheService;
use App\Services\IMobileService;

/**
 * Description of MobileServiceImpl
 *
 * @author ownfi
 */
class MobileServiceImpl implements IMobileService{

    private $cacheService;

    public function __construct(ICacheService $cacheService) {
        $this->cacheService = $cacheService;
    }

    public function sendMessage($phoneNum, $message) {
        //$phoneNum = 15051877991;
        $statusStr = array(
            "000" => "短信提交成功",
            "-01" => "账号余额不足",
            "-02" => "未开通接口授权",
            "-03" => "账号密码错误",
            "-04" => "参数个数不对或者参数类型错误",
            "-110" => "IP被限制",
            "-12" => "	其他错误",
        );
        $url="http://service.winic.org:8009/sys_port/gateway/index.asp?";
        $data = "id=%s&pwd=%s&to=%s&content=%s&time=";
        $id = iconv("UTF-8","GB2312","乐帮到家");
        $pwd = 'lb4008004703';
        try{
            $content = @iconv("UTF-8","GBK//IGNORE",$message);
        }catch (\Exception $e){
            $content = false;
        }
        if (empty($content)){
            $content = $message;
        }
        $rdata = sprintf($data, $id, $pwd, $phoneNum, $content);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST,1);
        curl_setopt($ch, CURLOPT_POSTFIELDS,$rdata);
        curl_setopt($ch, CURLOPT_URL,$url);
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
        $result = curl_exec($ch);
        curl_close($ch);
        $result_list = explode('/',$result);
        $code = $result_list[0];

        event(new SmsSent($phoneNum,$message,$code,@$statusStr[$code]));
        return $code == "000";
    }

    public function smsVerify($phoneNum, $verifyCode = null) {
        if ($verifyCode === null) {
            $verifyCode = random(6,'PNUMBER');
            $this->cacheService->smsVerifyCode($phoneNum, $verifyCode);
            $message = sprintf("【%s】您的验证码是：%s", config('app.name'),$verifyCode);
            if (isMock()){
                app()->make('debugbar')->addMessage($message);
                return true;
            }
            return $this->sendMessage($phoneNum, $message);
        } else {
            return $verifyCode == $this->cacheService->smsVerifyCode($phoneNum);
        }
    }

    public function smsLog($phone, $content, $code, $result)
    {
        return SmsLog::create([
//            'sl_content'=>str_limit($content,97),
            'sl_content'=>$content,
            'sl_code'=>$code,
            'sl_phone'=>$phone,
            'sl_error'=>$result,
            'sl_add_ip'=>getip(),
        ]);
    }

}
